package com.atguigu.juc;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;


/**
 * @author ：MJS
 * @date ：Created in 2021/4/24  14:15
 * @description：出故障了，如何面对
 * 1  故障出现
 *java.util.ConcurrentModificationException
 * 2   导致原因
 *
 *
 * 3   解决方案
 *  3.1 new Vector<>();
 *  3.2  Collections.synchronizedList(new ArrayList<>());
 *  3.3  new CopyOnWriteArrayList<>();  写时复制技术
 *
 * 4   优化建议（同样的错误不能出第二次）
 * 读多写少的情况    有用CopyOnWriteArrayList<>();类解决线程安全问题
 */
public class NotSafeDemo {
    public static void main(String[] args) {

        Map<String,String>map=new HashMap<>();
        Map<String,String>map1=Collections.synchronizedMap(new HashMap<>());
        Map<String,String>map2=new ConcurrentHashMap<>();


        for (int i = 1; i <=30; i++) {
            new Thread(() -> {
                map2.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,6));
                System.out.println(map2);
            }, String.valueOf(i)).start();
        }
    }

    public static void listNotSafe(String[] args) {
        List<String> list = new ArrayList<>();
        List<String> list1 = new Vector<>();
        List<String>list2= Collections.synchronizedList(new ArrayList<>());
        List<String>list3 =new CopyOnWriteArrayList<>();

        for (int i = 1; i <=30; i++) {
            new Thread(() -> {
                list3.add(UUID.randomUUID().toString().substring(0,6));
                System.out.println(list3);
            }, String.valueOf(i)).start();
        }
    }

    public static void SetNotSage(String[] args) {

        Set<String>set=new HashSet<>();
        Set<String>set1=Collections.synchronizedSet(new HashSet<>());
        Set<String>set2=new CopyOnWriteArraySet<>();

        for (int i = 1; i <=30; i++) {
            new Thread(() -> {
                set2.add(UUID.randomUUID().toString().substring(0,6));
                System.out.println(set2);
            }, String.valueOf(i)).start();
        }
    }
}
